package com.dorm;

import java.io.*;
import java.util.*;
//import org.apache.poi.ss.usermodel.*;
//import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import org.apache.poi.ss.usermodel.*;
//import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

class Building {
    private String buildID; 
    private String type;    //男生宿舍M，女生宿舍F
    private int capacity;    //一栋拥有的房间
    public List<Room> rooms; //分配的房间 

    public Building(String buildID, String type, int capacity) {
	    this.buildID = buildID;
	    this.type = type;
	    this.capacity = capacity;
	    this.rooms = new ArrayList<>();
    }
    
    public void addRoom(Room room) {
    	if (rooms.size() == capacity) {
            System.out.println("该楼的房间已全部分配完毕，最大房间数: " + capacity);
    	} else {
    	rooms.add(room);
    	}
    }
    
    public void removeRoom(String roomID) {
    	Iterator<Room> iterator = rooms.iterator();
    	while (iterator.hasNext()) {
    	    Room element = iterator.next();
    	    if (element.getroomID().equals(roomID)) {
    	        iterator.remove();
    	        break;
    	    }
    	}    	
    }
    
    public String getBuildingIDByroomID(String roomID) {
    	String bID = null;
    	Iterator<Room> iterator = rooms.iterator();
    	while (iterator.hasNext()) {
    	    Room element = iterator.next();
    	    if (element.getroomID().equals(roomID)) {
    	    	bID = this.getbuildID();
    	        break;
    	    }
    	}
        return bID;
    }
    
    public Room GetRoomByroomID (String roomID) {
    	Room room1 = null;
    	Iterator<Room> iterator = rooms.iterator();
    	while (iterator.hasNext()) {
    	    Room element = iterator.next();
    	    if (element.getroomID().equals(roomID)) {
    	    	room1 = element;
    	        break;
    	    }
    	}
        return room1;
    }
    
    public int getRoomCount() {
    	return rooms.size();
    }
    
    public String getbuildID() {
        return buildID;
    }
    
    public String gettype() {
        return type;
    }

    public int getcapacity() {
        return capacity;
    }
    
    public void printBuildingInfo() {
        System.out.println("======================================");
        System.out.print("  楼号: " + this.buildID);
        System.out.print("  男/女生楼: " + this.type);
        System.out.print("  宿舍数量: " + this.capacity);
        System.out.println();
    }
    
    
}

class Room {
    private String roomID; 
    private String type;    //男生宿舍M，女生宿舍F
    private int capacity;    //能住几人
    public List<Student> students; //分配的学生 


    public Room(String roomID, String type, int capacity) {
	    this.roomID = roomID;
	    this.type = type;
	    this.capacity = capacity;
	    this.students = new ArrayList<>();
    }
    
    public void addStudent(Student student) {
    	students.add(student);
    }
    
    public void removeStudent(int studentID) {
    	Iterator<Student> iterator = students.iterator();
    	while (iterator.hasNext()) {
    	    Student element = iterator.next();
    	    if (element.getStudentID() == studentID) {
    	        iterator.remove();
    	        break;
    	    }
    	}    	
    }

    public String getRoomIDByStudentID(int studentID) {
    	String rID = null;
    	Iterator<Student> iterator = students.iterator();
    	while (iterator.hasNext()) {
    	    Student element = iterator.next();
    	    if (element.getStudentID() == studentID) {
    	    	rID = this.getroomID();
    	        break;
    	    }
    	}
        return rID;
    }
    
    public int getStudentCount() {
    	return students.size();
    }

    public String getroomID() {
        return roomID;
    }
    
    public String gettype() {
        return type;
    }

    public int getcapacity() {
        return capacity;
    }
    
    public void printRoomInfo() {
        System.out.println("======================================");
        System.out.print("  宿舍号: " + this.roomID);
        System.out.print("  男/女生: " + this.type);
        System.out.print("  宿舍能住人数: " + this.capacity);
        System.out.println();
    }
    
    
}


class Student {
    private String name, gender, major, className;
    private int studentID, age;

    public Student(String name, String gender, int studentID, int age, String major, String className) {
        this.name = name;
        this.gender = gender;
        this.studentID = studentID;
        this.age = age;
        this.major = major;
        this.className = className;
    }


    // 输出学生信息，包括字母成绩
    public void printStudentInfo() {
//        System.out.println("======================================");
        System.out.println("姓名: " + name);
        System.out.println("性别: " + gender);
        System.out.println("学号: " + studentID);
        System.out.println("年龄: " + age);
        System.out.println("专业: " + major);
        System.out.println("班级: " + className);
    }
    
    public int getStudentID() {
        return studentID;
    }

    public String getName() {
        return name;
    }
    
    public String getGender() {
        return gender;
    }

    public int getAge() {
        return age;
    }

    public String getMajor() {
        return major;
    }
    
    public String getClassName() {
        return className;
    }
    
}

class BuildingManager{
	public List<Building> buildingDatabase;
	
	public BuildingManager() {
		buildingDatabase = new ArrayList<>();
	}
	
	public void AddBuilding(Building building) {
		buildingDatabase.add(building);
	}
	
	public Building getBuilding(String roomID) {
		Building building = null;
    	Iterator<Building> iterator = buildingDatabase.iterator();
    	while (iterator.hasNext()) {
    		Building element = iterator.next();
    	    if (element.getBuildingIDByroomID(roomID) != null) {
    	        building = element;
    	        break;
    	    }
    	}
    	return building;
	}
	
	public Building AddRoomByBuildID(String buildID, Room room) {
		Building building1 = null;
		for (Building building : buildingDatabase) {
			if (building.getbuildID().equals(buildID)) {
				building.addRoom(room);
				building1 =  building;
			}
		}
		return building1;
	}
	
	public Building inputBuilding(Scanner scanner) {
//        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入宿舍楼号: ");
        String buildingID = scanner.nextLine();
        System.out.print("男生/女生（M/F）: ");
        String type = scanner.nextLine();
        System.out.print("该楼共有宿舍数量（整数数值）: ");
        int capacity = scanner.nextInt();
//        scanner.close();

        Building building = new Building(buildingID, type, capacity);
        return building;
	}
	
}

class RoomManager{
	public List<Room> roomDatabase;
	
	public RoomManager() {
		roomDatabase = new ArrayList<>();
	}
	
	public void AddRoom(Room room) {
		roomDatabase.add(room);
	}
	
	public Room getRoomByStudentID(int studentID) {
		Room room = null;
    	Iterator<Room> iterator = roomDatabase.iterator();
    	while (iterator.hasNext()) {
    		Room element = iterator.next();
    	    if (element.getRoomIDByStudentID(studentID) != null) {
    	        room = element;
    	        break;
    	    }
    	}
    	return room;
	}

	public Room getRoomByRoomID(String roomID) {
		Room room = null;
    	Iterator<Room> iterator = roomDatabase.iterator();
    	while (iterator.hasNext()) {
    		Room element = iterator.next();
    	    if (element.getroomID().equals(roomID)) {
    	        room = element;
    	        break;
    	    }
    	}
    	return room;
	}

	public Room inputRoom() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入宿舍号: ");
        String roomID = scanner.nextLine();
        System.out.print("男生/女生（M/F）: ");
        String type = scanner.nextLine();
        System.out.print("该宿舍能住人数（整数数值）: ");
        int capacity = scanner.nextInt();
//        scanner.close();

        Room room = new Room(roomID, type, capacity);
        return room;
	}
	
}

class StudentManager {
	public List<Student> studentDatabase;
	
	public StudentManager() {
		studentDatabase = new ArrayList<>();
	}

    // 添加学生
    public void addStudent(Student student) {
        studentDatabase.add(student);
    }

    // 根据学号获取学生
    public Student getStudentByID(int studentID) {
    	Student student1 = null;
    	for (Student student : studentDatabase) {
    		if (student.getStudentID() == studentID) {
    			student1 = student;
    			break;
    		}
    	}
    	return student1;
    }

    // 显示所有学生信息
    public void displayAllStudents() {
        for (Student student : studentDatabase) {
            student.printStudentInfo();
            System.out.println("---------------------------");
        }
    }

    // 从Excel导入学生数据
    public void importStudentsFromExcel(String importFilePath) throws Exception {
    	FileInputStream file = new FileInputStream(new File(importFilePath));
    	Workbook workbook = new XSSFWorkbook(file);
    	Sheet sheet = workbook.getSheetAt(0);
    	
    	Iterator<Row> rowIterator = sheet.iterator();
    	rowIterator.next();
    	while (rowIterator.hasNext()) {
    		Row row = rowIterator.next();
    		String name = row.getCell(0).getStringCellValue();
    		String gender = row.getCell(1).getStringCellValue();
			int studentID = (int) row.getCell(2).getNumericCellValue();
			int age = (int) row.getCell(3).getNumericCellValue();
			String major = row.getCell(4).getStringCellValue();
			String className = row.getCell(5).getStringCellValue();
//			String roomID = row.getCell(6).getStringCellValue();
			
			// 将所有学生添加到主数据库中
            Student student = new Student(name, gender, studentID, age, major, className);
            this.addStudent(student);
  			
			
    		Iterator<Cell> cellIterator = row.cellIterator();
    		while (cellIterator.hasNext()) {
    			Cell cell = cellIterator.next();
    			switch (cell.getCellType()) {
    			case STRING:
    				System.out.print(cell.getStringCellValue() + "\t");
    				break;
    			case NUMERIC:
    				System.out.print((int) cell.getNumericCellValue() + "\t");
    				break;
    			}
    			
    		}
    		System.out.println();
    	}

    }
}

public class DormitoryManagementSystem {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        StudentManager studentManager = new StudentManager();
        RoomManager roomManager = new RoomManager();
        BuildingManager buildingManager = new BuildingManager();

        // 设置静态的Excel文件路径和输出文件路径
        String importFilePath = "D:\\eclipse-java-2024-09-R-win32-x86_64\\javaDemo\\student_data.xlsx";   // Excel文件的静态路径
        String exportFilePath =  "D:\\eclipse-java-2024-09-R-win32-x86_64\\javaDemo\\student_data.txt";   // TXT文件的静态路径

        while (true) {
            System.out.println("欢迎使用学生宿舍管理系统");
            System.out.println("1. 添加宿舍楼");
            System.out.println("2. 添加宿舍");
            System.out.println("3. 从Excel导入学生数据");
            System.out.println("4. 分配学生宿舍");
            System.out.println("5. 导出宿舍分配情况到文件");
            System.out.println("6. 退出");
            System.out.print("请选择操作: ");
            
            // 检查输入是否为整数
            if (!scanner.hasNextInt()) {
                System.out.println("无效输入，请输入一个数字。");
                scanner.next(); // 清除错误输入
                continue;
            }

            int choice = scanner.nextInt();
            scanner.nextLine(); // 消耗换行符

            if (choice == 1) {
            	Building building1 = buildingManager.inputBuilding(scanner);
                buildingManager.AddBuilding(building1);
                for (Building building : buildingManager.buildingDatabase) {
                	building.printBuildingInfo();
                };
            } else if (choice == 2) {
            	Room room = roomManager.inputRoom();
                roomManager.AddRoom(room);
                System.out.print("请输入所属楼号: ");
                String buildID = scanner.nextLine();
            	Building building = buildingManager.AddRoomByBuildID(buildID, room);
            	room.printRoomInfo();
                System.out.print("  宿舍号："+room.getroomID()+" 加入的宿舍楼号是: " + buildingManager.getBuilding(room.getroomID()).getbuildID());
                System.out.println();
                System.out.println("-----------------------------------------");

            } else if (choice == 3) {
                try {
                    studentManager.importStudentsFromExcel(importFilePath);
                    System.out.println("学生数据导入成功！");
//                    studentManager.displayAllStudents();
                } catch (Exception e) {
                    System.out.println("导入数据时发生错误: " + e.getMessage());
                }
            } else if (choice == 4) {
	              System.out.print("请输入学号: ");
	              int studentID = scanner.nextInt();
	              scanner.nextLine();   //消耗换行符
	              Student student = studentManager.getStudentByID(studentID);
	              if (student != null) {
	                  student.printStudentInfo();
	                  System.out.println("-----------------------------------------");
		              System.out.print("请输入要分配到的宿舍号: ");
		              String roomID = scanner.nextLine();
		              Building building = buildingManager.getBuilding(roomID);
 		              building.GetRoomByroomID(roomID).addStudent(student);
		              System.out.println(roomID + "号宿舍共学生人数：" + roomManager.getRoomByRoomID(roomID).getStudentCount());
	              } else {
	                  System.out.println("未找到该学号的学生。");
	              }
            } else if (choice == 5) {
                    try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(exportFilePath), "UTF-8"))) {
                      for (Building building : buildingManager.buildingDatabase) {
                          //for room
                    	  for (Room room : building.rooms) {
                    		  for (Student student : room.students) {
                    			  writer.write("楼号：" + building.getbuildID()+"，宿舍号："+room.getroomID()+"，姓名："+student.getName()+"，性别："+student.getGender()+"，学号："+student.getStudentID()+"，年龄："+student.getAge()+"，专业："+student.getMajor()+"，班级："+student.getClassName());
                    			  writer.newLine();
                    		  }
                    	  }
                      }
                    System.out.println("宿舍分配已成功导出到文件。");
                } catch (IOException e) {
                    System.out.println("导出时发生错误: " + e.getMessage());
                }
            } else if (choice == 6) {
                System.out.println("感谢使用学生宿舍管理系统！");
                break;
            } else {
                System.out.println("无效操作，请重新选择！");
            }
        }

        scanner.close();
    }
    
}
